package com.tcxhb.job.agent.server.thread;

import com.tcxhb.job.agent.constants.BestJobConfig;
import com.tcxhb.job.agent.service.JobServerApi;
import com.tcxhb.job.common.Thread.NamedThreadFactory;
import com.tcxhb.job.common.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

/**
 * @Description:
 * @Auther: tcxhb
 * @Date: 2023/11/5
 */
@Slf4j
public class JobRegisterThread implements InitializingBean, DisposableBean {
    @Autowired
    private JobServerApi jobServerApi;
    @Autowired
    private BestJobConfig config;
    private ScheduledExecutorService agentBeatPool = Executors.newScheduledThreadPool(1,
            new NamedThreadFactory("agent-beat", true));

    @Override
    public void destroy() throws Exception {
        Integer port = config.getPort();
        String appName = config.getAppName();
        log.error("agent-offline:" + appName + "," + config.getAgentHost() + ":" + port + "");
        jobServerApi.offline(config.getAgentHost(), port, appName);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        init();
    }

    public void init() {
        config.setAgentHost(IPUtils.getIp());
        agentBeatPool.submit(() -> register());
    }

    public void register() {
        //注册
        Integer port = config.getPort();
        String appName = config.getAppName();
        log.info("agent-register:" + appName + "," + config.getAgentHost() + ":" + port + "");
        jobServerApi.register(config.getAgentHost(), port, appName);
    }
}
